import axios from 'axios'
import { ElMessage } from 'element-plus'

const errorCode = {
  401: '认证失败，无法访问系统资源',
  403: '当前操作没有权限',
  404: '访问资源不存在',
  default: '系统未知错误，请反馈给管理员',
}

const Api = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL_PREFIX,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
  timeout: 30000,
})

// 请求拦截器
Api.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    // 错误抛到业务代码
    error.data = {}
    error.data.msg = '服务器异常'
    return Promise.resolve(error)
  },
)

// 响应拦截器
Api.interceptors.response.use(
  (response) => {
    const code = response.data.code || 200
    const msg = errorCode[code] || response.data.msg || errorCode['default']
    // 二进制数据则直接返回
    if (
      response.request.responseType === 'blob' ||
      response.request.responseType === 'arraybuffer'
    ) {
      return response.data
    }
    if (code !== 200) {
      switch (code) {
        case 400:
          ElMessage.error(msg)
          break
        case 401:
          //
          break
        case 403:
          //
          break
        // ...
        case 500:
          ElMessage.error(msg)
          break
        // ...
        default:
          throw new Error('未知错误')
      }
      return Promise.reject(new Error(msg))
    } else {
      return response.data
    }
  },
  (error) => {
    const status = error['response.status']
    const message = error['response.data.msg'] || errorCode['default']
    switch (status) {
      case 400:
        error.message = message || '请求错误'
        break
      case 401:
        error.message = message || '未授权'
        break
      case 403:
        error.message = message || '拒绝访问'
        break
      case 404:
        error.message = message || '请求地址出错'
        break
      case 408:
        error.message = message || '请求超时'
        break
      case 500:
        error.message = message || '服务器内部错误'
        break
      case 501:
        error.message = message || '服务未实现'
        break
      case 502:
        error.message = message || '网关错误'
        break
      case 503:
        error.message = message || '服务不可用'
        break
      case 504:
        error.message = message || '网关超时'
        break
      case 505:
        error.message = message || 'HTTP 版本不受支持'
        break
    }
    ElMessage.error(error.message)
    return Promise.reject(error)
  },
)

export default Api
